import fs from 'fs'
import path from 'path'

const copyFile = (readPath: any, writePath: any) => {
    const getWritePath = (oldPath: any) => {
        let newPath = oldPath;
        const getPath = (oldPath: any) => {
            if(fs.existsSync(oldPath)){
                const temp = path.parse(oldPath)
                newPath = path.join(temp.dir, temp.name + 'Copy' + temp.ext)
                getPath(newPath)
            }
            return newPath
        }
        getPath(oldPath);
        return newPath
    }
    return new Promise((resolve, reject) => {
        fs.readFile(readPath, 'utf-8', (err, data) => {
            if(err) throw err;
            let newPath = getWritePath(writePath)
            fs.writeFile(newPath, data, 'utf8', (err) => {
                if (err) {
                    reject(false)
                } else {
                    resolve(true)
                }
            });
        })
    })
}

export const createFile = async (uri: string, type: string) => {
    if(type === 'vue2'){
        let filePath = path.join(uri.substring(1), './index.vue');
        return await copyFile(path.join(__dirname, '../public/template/index.vue2'), filePath);
    }
    else if(type === 'vue3'){
        let filePath = path.join(uri.substring(1), './index.vue');
        return await copyFile(path.join(__dirname, '../public/template/index.vue3'), filePath);
    }
}
